<template>
  <div class="my-section">
    <div class="title-area">
      <van-nav-bar
        title="我的"
        left-text=""
        right-text=""
        left-arrow
        @click-left="onClickLeft"
      />
      <div class="my-area-con">
        <van-card :title="user.username" :thumb="user.avatar">
          <template #tags v-if="user.roles" style="margin: 10px 0 0 0">
            <van-tag
              plain
              type="danger"
              v-for="item in user.roles"
              :key="item.id"
            >
              {{ item.name }}
            </van-tag>
          </template>
          <template #bottom>
            <span>当前角色：{{ currentRoleName() }}</span>
          </template>
          <template #footer>
            <van-button size="small" @click="goDetail">详情</van-button>
            <van-button size="small" @click="show = true">切换账号</van-button>
          </template>
        </van-card>
        <van-action-sheet
          v-model="show"
          :actions="roleOptions"
          @select="onSelect"
        />
        <van-cell title="销售订单" icon="cart-o" is-link to="index" />
        <van-cell title="在线客户" icon="friends-o" is-link to="index" />
        <van-cell title="使用帮助" icon="notes-o" is-link to="index" />
      </div>
    </div>
  </div>
</template>

<script>
import { Toast } from "vant";
import { mapGetters } from "vuex";
import { updateUserDefaultRole, getUserProfile } from "@/api/system/user";
import { listSimpleRoles } from "@/api/system/role";
export default {
  name: "Message",
  data() {
    return {
      show: false,
      show: false,
      user: {},
      roleGroup: {},
      roleOptions: [],
    };
  },
  computed: {
    ...mapGetters([
      "sidebar",
      "avatar",
      "nickname",
      "device",
      "roles",
      "currentRoleId",
    ]),
  },
  created() {
    this.getUser();
    this.listSimpleRoles();
  },
  methods: {
    onClickLeft() {
      this.$router.go(-1);
    },
    getUser() {
      getUserProfile().then((response) => {
        this.user = response.data;
      });
    },
    currentRoleName() {
      return this.roleOptions.filter(
        (item) => this.currentRoleId === item.id
      )?.[0]?.name;
    },
    updateUserDefaultRole(roleId) {
      updateUserDefaultRole(roleId).then(() => {
        Toast("切换用户角色成功");
        //更新角色权限
        this.$store.dispatch("getUserInfo");
      });
    },
    // 获得角色列表 TODO 后续需优化 加载一次后面其他地方也使用
    listSimpleRoles() {
      listSimpleRoles().then((response) => {
        // 处理 roleOptions 参数
        this.roleOptions = [];
        // this.roleOptions.push(...response.data)
        this.roleOptions = response.data.filter((item) =>
          this.roles.includes(item.code)
        );
      });
    },
    onSelect(item) {
      this.show = false;
      this.updateUserDefaultRole(item.id);
    },
    goDetail() {
      this.$router.push({
        name: "MMyDetail",
      });
    },
  },
};
</script>

<style lang="scss" scoped></style>
